import { Request, Response } from 'express';
import { CourseService } from '../services/course.service';

const courseService = new CourseService();

export class CourseController {
    async getCourses(req: Request, res: Response) {
        try {
            const courses = await courseService.getCourses();
            res.json({ data: courses });
        } catch (error) {
            res.status(500).json({ message: '服务器错误' });
        }
    }

    async getCourseById(req: Request, res: Response) {
        try {
            const courseId = parseInt(req.params.id);
            const course = await courseService.getCourseById(courseId);
            if (!course) {
                return res.status(404).json({ message: '课程不存在' });
            }
            res.json({ data: course });
        } catch (error) {
            res.status(500).json({ message: '服务器错误' });
        }
    }

    async searchCourses(req: Request, res: Response) {
        try {
            const { q } = req.query;
            if (!q || typeof q !== 'string') {
                return res.status(400).json({ message: '搜索关键词不能为空' });
            }
            const courses = await courseService.searchCourses(q);
            res.json({ data: courses });
        } catch (error) {
            res.status(500).json({ message: '服务器错误' });
        }
    }

    async toggleFavorite(req: Request, res: Response) {
        try {
            const { courseId } = req.body;
            const userId = 1; // 实际应该从token中获取
            const result = await courseService.toggleFavorite(userId, courseId);
            res.json({ message: result ? '收藏成功' : '取消收藏' });
        } catch (error) {
            res.status(500).json({ message: '服务器错误' });
        }
    }
}
